//
//  DetailViewController.m
//  ZAKER
//
//  Created by dllo on 15/8/29.
//  Copyright (c) 2015年 蓝鸥科技. All rights reserved.
//

#import "DetailViewController.h"


@interface DetailViewController ()<UITableViewDataSource, UITableViewDelegate>


@property (nonatomic,retain) UITableView *tableView;
@property (nonatomic, retain) NSMutableArray *myArray; // 存放详情的内容
@property (nonatomic, retain) NSMutableArray *imageArray; // 存放照片
@property (nonatomic,retain) NSMutableArray *urlArray;
@property (nonatomic, copy) NSString *webUrl; // 存放刷新的网址
@property (nonatomic, retain) MBProgressHUD *mb;


@end

@implementation DetailViewController

-(void)dealloc
{
    _tableView.delegate = nil;
    
    [_tableView release];
    [_myArray release];
    [_imageArray release];
    [_urlArray release];
    [_webUrl release];
    [_mb release];
    [_cityCode release];
    
    
    [super dealloc];
    
}


-(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    
    if (self) {
        
        self.myArray = [NSMutableArray array];
        self.imageArray = [NSMutableArray array];
        self.urlArray = [NSMutableArray array];
        
    }
    
    return self;
    
}

- (void)viewDidLoad
{
    
    [super viewDidLoad];
    
    UIWindow *window = [[[UIApplication sharedApplication]delegate]window];
    self.mb = [[MBProgressHUD alloc]initWithView:window];
    [window addSubview:_mb];
    _mb.labelText = @"正在加载";
    [_mb show:YES];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)10 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
        
        if (_mb != nil) {
            
            [_mb removeFromSuperview];
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"数据加载失败" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
            [alert  show];
            [alert release];
            
        }
    });
    

    [self myConnection];
    [self createTableView];
    
    [self addHeader];
    [self addFotter];
    
}

#pragma mark - 数据解析

-(void)myConnection
{
    NSArray *arr = [NSArray arrayWithObjects:@"10000", @"1", @"4",@"7", @"3", nil];
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString *cityCode = [user objectForKey:@"cityCode"];
   
    NSString *str  = [arr objectAtIndex:(self.efaIndex - 1000)];
    [MyAFNetworking GetWithURL:[NSString stringWithFormat:JingXuan, str, cityCode] dic:nil data:^(id responsder) {
        
    [self.myArray removeAllObjects];
    [self.imageArray removeAllObjects];
        
#warning 还有的城市无内容也不推荐
        if ([responsder[@"msg"] isEqualToString:@"没有内容"]) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"当前城市无此内容" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
            alert.tag = 20;
            [alert show];
            
        }
        
    NSMutableDictionary *dict = [responsder objectForKey:@"data"];
    NSDictionary *myDic = [dict objectForKey:@"info"];
        
#warning 如果这个城市没有这个东西会有一个字段key值tips
        if (myDic[@"tips"]) {
            
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"当前城市无此类别" message:@"已经为你推荐附近城市" delegate:self cancelButtonTitle:@"确定，谢谢" otherButtonTitles:nil];
            [alert show];
            
        }
        
        
    self.webUrl = [myDic objectForKey:@"next_url"];
    
    NSArray *array = dict[@"weekends"];
    for (int i = 0; i < array.count; i++) {
        NSString *str = [[[[array objectAtIndex:i] objectForKey:@"thumbnail_medias"] lastObject] objectForKey:@"m_url"];
        
        NSString *urlStr = [[[array objectAtIndex:i] objectForKey:@"weekend"] objectForKey:@"content_url"];
        
        [self.urlArray  addObject:urlStr];
        
        [self.imageArray addObject:str];
        DetailShowModel *model = [[DetailShowModel alloc]init];
        [model setValuesForKeysWithDictionary:[array objectAtIndex:i]];
        [self.myArray addObject:model];
        [model release];
    }
    [self.tableView reloadData];
    [_mb hide:YES];
    _mb = nil;
    [_mb release];
}];
}

#warning 额外加的
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == 20) {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

-(void)sendIndex:(NSInteger)index
{
    
    self.efaIndex = index;
    
}

#pragma mark - 视图将要出现

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    switch (_efaIndex) {
        case 1000:
            self.title = @"精选";
            break;
        case 1001:
            self.title = @"演艺";
            break;
        case 1002:
            self.title = @"度假";
            break;
        case 1003:
            self.title = @"电影";
            break;
        case 1004:
            self.title = @"活动";
            break;
            
    }
}

#pragma mark - 收藏按钮的点击事件

-(void)collectionAction:(UIButton *)button
{
    
    [button setTitleColor:RGBACOLOR(0, 191, 255, 1) forState:UIControlStateNormal];
    
    DetailShowModel *titleModel = [_myArray objectAtIndex:(button.tag - 100)];
    NSString *imageUrlStr = [_imageArray objectAtIndex:(button.tag - 100)];
    NSString *urlStr = [_urlArray objectAtIndex:button.tag - 100];
    
    DetailShowModel *model = [NovalDataBase selectOneWith:titleModel.title];
    
    if (model != nil) {
        
        [button setTitle:@"❤️喜欢" forState:UIControlStateNormal];
        DetailShowModel *model = [DetailShowModel holidayWithTitle:titleModel.title  address:titleModel.address  image:imageUrlStr urlStr:urlStr];
        [NovalDataBase deleteHolidayWithModel:model];
        
    } else {
        
        [button setTitle:@"已收藏" forState:UIControlStateNormal];
        DetailShowModel *model = [DetailShowModel holidayWithTitle:titleModel.title  address:titleModel.address  image:imageUrlStr urlStr:urlStr];
        [NovalDataBase insertHolidayWithModel:model];
        
    }
}


#pragma mark - 创建tableView, 以及实现协议方法

-(void)createTableView
{
    
    self.tableView = [[[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 49)] autorelease];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableView];
//    [_tableView release];
    
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    if (_efaIndex == 1000 || _efaIndex == 1002 || _efaIndex == 1003) {
        
        return _myArray.count;
        
    } else if (_efaIndex == 1001) {
        
        return _myArray.count / 2;
        
    } else if (_efaIndex == 1004) {
        
        return _myArray.count / 3;
        
    }

    return 0;
    
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (self.efaIndex == 1000) {
        
        self.title = @"精选";
        JXuanTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuseJ"];
        
        if (cell == nil) {
            
         cell = [[[JXuanTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"reuseJ"] autorelease];
            
        }
        
        DetailShowModel *model = [_myArray objectAtIndex:indexPath.row];
        
        [cell.MyImage sd_setImageWithURL:[NSURL URLWithString:[_imageArray objectAtIndex:indexPath.row]] placeholderImage:[UIImage imageNamed:@"HNews.jpg"]];
        cell.titleLabel.text = model.title;
        cell.addressLabel.text = model.address;
        cell.timeLabel.text  = [NSString stringWithFormat:@"%@ %@", model.time_str, model.category_name];
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
        
    } else if (self.efaIndex == 1001) {
        
        PerformTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuseP"];
        if (cell == nil) {
            
            cell = [[[PerformTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"reuseP"] autorelease];
        }
        
        DetailShowModel *leftModel = [_myArray objectAtIndex:indexPath.row * 2];
        
        [cell.leftMyImage sd_setImageWithURL:[NSURL URLWithString:[_imageArray objectAtIndex:indexPath.row * 2]] placeholderImage:[UIImage imageNamed:@"HNews.jpg"]];
        cell.leftTitleLabel.text = leftModel.title;
        
        DetailShowModel *rightModel = [_myArray objectAtIndex:indexPath.row * 2 + 1];
        
        [cell.rightMyImage sd_setImageWithURL:[NSURL URLWithString:[_imageArray objectAtIndex:indexPath.row * 2 + 1]] placeholderImage:[UIImage imageNamed:@"HNews.jpg"]];
        cell.rightTitleLabel.text = rightModel.title;
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
        
    } else if (self.efaIndex == 1002) {
        
        HolidayTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuseH"];
        
        if (cell == nil) {
            
            cell = [[[HolidayTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"reuseH"] autorelease];
            
        }
        
        DetailShowModel *model = [_myArray objectAtIndex:indexPath.row];
        
        cell.titleLabel.text = model.title;
        cell.addressLabel.text = model.address;
        [cell.MyImage sd_setImageWithURL:[NSURL URLWithString:[_imageArray objectAtIndex:indexPath.row]] placeholderImage:[UIImage imageNamed:@"HNews.jpg"]];
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.collButton.tag = 100 + indexPath.row;
        
        DetailShowModel *selectModel = nil;
        selectModel = [NovalDataBase selectOneWith:model.title];
        
        if (selectModel != nil) {
            
            [cell.collButton setTitle:@"已收藏" forState:UIControlStateNormal];
           
        } else {
            
            [cell.collButton setTitle:@"❤️喜欢" forState:UIControlStateNormal];
            
        }
        
        [cell.collButton setTitleColor:RGBACOLOR(0, 191, 255, 1) forState:UIControlStateNormal];
        [cell.collButton addTarget:self action:@selector(collectionAction:) forControlEvents:UIControlEventTouchUpInside];
        
        return cell;
        
    } else if (self.efaIndex == 1003) {
        
        MovieTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuseM"];
        
        if (cell == nil) {
            
            cell = [[[MovieTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"reuseM"] autorelease];
            
        }
        
        DetailShowModel *model = [_myArray objectAtIndex:indexPath.row];
        
        [cell.MyImage sd_setImageWithURL:[NSURL URLWithString:[_imageArray objectAtIndex:indexPath.row]] placeholderImage:[UIImage imageNamed:@"HNews.jpg"]];
        cell.titleLabel.text = model.title;
        cell.addressLabel.text = model.pos_str;
        cell.timeLabel.text  = model.time_str;
        
       cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
        
    } else if (self.efaIndex == 1004) {
        
        ActivityTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuseA"];
        
        if (cell == nil) {
            
            cell = [[[ActivityTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"reuseA"] autorelease];
            
        }
        if ([_imageArray count] != 0) {
            
                DetailShowModel *modelLeft = [_myArray objectAtIndex:indexPath.row * 3];
                [cell.leftMyImage sd_setImageWithURL:[NSURL URLWithString:[_imageArray objectAtIndex:indexPath.row * 3]] placeholderImage:[UIImage imageNamed:@"HNews.jpg"]];
                cell.leftTitleLabel.text = modelLeft.title;
            
            
                [cell.centerMyImage sd_setImageWithURL:[NSURL URLWithString:[_imageArray objectAtIndex:indexPath.row * 3 + 1]] placeholderImage:[UIImage imageNamed:@"HNews.jpg"]];
                DetailShowModel *modelCenter = [_myArray objectAtIndex:indexPath.row * 3 + 1];
                cell.centerTitleLabel.text = modelCenter.title;
        
            
                [cell.rightMyImage sd_setImageWithURL:[NSURL URLWithString:[_imageArray objectAtIndex:indexPath.row * 3 + 2]] placeholderImage:[UIImage imageNamed:@"HNews.jpg"]];
                DetailShowModel *modelRight = [_myArray objectAtIndex:indexPath.row * 3 + 2];
                cell.rightTitleLabel.text = modelRight.title;
            
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
            
        }
    }
    
    return [[UITableViewCell alloc] init];
    
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (_efaIndex == 1000) {
        
        return 500 * myHeight;
        
    } else if (_efaIndex == 1001) {
        
        return 200 *  myHeight;
        
    } else if (_efaIndex == 1002) {
        
        return 245 * myHeight;
        
    } else if (_efaIndex == 1003) {
        
        return 500 * myHeight;
        
    } else if (_efaIndex == 1004) {
        
        return 150 * myHeight;
        
    }
    
    return 0;
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    EnyerViewController *enter = [[EnyerViewController alloc]init];
    NSString *str = [self.urlArray objectAtIndex:indexPath.row];
    [enter sendWithUrl:str];
    [self.navigationController pushViewController:enter animated:YES];
    [enter release];
    
}

#pragma mark - 刷新加载

-(void)addHeader
{
    [self.tableView addHeaderWithCallback:^{
        
        [self myConnection];
        [self.tableView headerEndRefreshing];
        
    }];
}

-(void)addFotter
{
    
    [self.tableView addFooterWithCallback:^{
        
        [MyAFNetworking GetWithURL:_webUrl dic:nil data:^(id responsder) {
            
            NSMutableDictionary *dict = [responsder objectForKey:@"data"];
            NSDictionary *myDic = [dict objectForKey:@"info"];
            self.webUrl = [myDic objectForKey:@"next_url"];
            NSArray *array = dict[@"weekends"];
            
            for (int i = 0; i < array.count; i++) {
                
                NSString *str = [[[[array objectAtIndex:i] objectForKey:@"thumbnail_medias"] lastObject] objectForKey:@"m_url"];
                NSString *urlStr = [[[array objectAtIndex:i] objectForKey:@"weekend"] objectForKey:@"content_url"];
                
                [self.urlArray  addObject:urlStr];
                [self.imageArray addObject:str];
                
                DetailShowModel *model = [[DetailShowModel alloc]init];
                [model setValuesForKeysWithDictionary:[array objectAtIndex:i]];
                [self.myArray addObject:model];
                [model release];
                
            }
            
            [self.tableView reloadData];
            [self.tableView footerEndRefreshing];
            
        }];
    }];
}


- (void)didReceiveMemoryWarning
{
    
    [super didReceiveMemoryWarning];
    
}



@end
